package com.colbby.datahouse.database;


public abstract class AbstractInserter<T> implements Inserter<T> {

	@Override
	public void insert(T entity) {
		//根据主键从数据库中获取对象
		//若数据库中找不到对象，则插入
		//若找到对象则对比
		//更新
		lock(entity);
		try {
			T old = findFromDatabase(entity);
			if(old == null) {
				insertInto(entity);
			} else {
				update(entity, old);
			}
		} finally {
			unlock(entity);
		}
	}
	
	protected abstract T findFromDatabase(T entity);
	
	protected abstract void insertInto(T entity);
	
	protected abstract void update(T newOne, T oldOne);
	
	protected abstract void lock(T entity);
	
	protected abstract void unlock(T entity);
}